package com.bentley.kotlindemo.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.bentley.kotlindemo.net.manager.NetworkStateManager
import com.bentley.kotlindemo.ui.widget.LoadingDialog
import java.lang.reflect.ParameterizedType

/**
 * <pre>
 *  ┌────────────────────────────────────────────
 *  │ @author  Lee  @date 2021/3/17 16:06
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ @desc
 *  └────────────────────────────────────────────
 * </pre>
 */
abstract class BaseActivity<T : ViewDataBinding, V : ViewModel> : AppCompatActivity() {
    protected lateinit var dataBinding: T
    protected lateinit var viewModel: V

    val loading by lazy { LoadingDialog(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(NetworkStateManager.instance)
        getBundleExtras(intent.extras)
        if (getLayoutId() != 0) {
            dataBinding = DataBindingUtil.setContentView(this, getLayoutId())
            dataBinding.lifecycleOwner = this

            viewModel = initViewModel()
            initView(savedInstanceState)
        } else
            throw  IllegalArgumentException("You must set layout id")
    }

    private fun initViewModel(): V {
        try {
            val pt =
                this.javaClass.genericSuperclass as ParameterizedType?
            val clazz =
                pt!!.actualTypeArguments[1] as Class<V>
            viewModel = ViewModelProviders.of(this)[clazz]
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return viewModel
    }

    fun showLoadingDialog() {
        if (!loading?.isShowing) {
            loading?.show()
        }
    }

    fun dismissLoadingDialog() {
        loading?.dismiss()
    }


    /**
     * 初始化数据
     */
    abstract fun initView(savedInstanceState: Bundle?)

    /**
     *  获取bundle 中的数据
     */
    open fun getBundleExtras(extras: Bundle?) {}

    /**
     * 获取当前布局id
     */
    abstract fun getLayoutId(): Int
}